import React, { useState, useEffect } from 'react';
import { NavBar, Button, Toast, Modal, Form, Input, Picker, Dialog } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import styles from './CourseSchedule.module.css';

function CourseSchedule() {
  const navigate = useNavigate();
  const [currentWeek, setCurrentWeek] = useState(1);
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [showCourseDetail, setShowCourseDetail] = useState(false);
  const [showAddModal, setShowAddModal] = useState(false);
  const [selectedCourse, setSelectedCourse] = useState(null);

  // 生成当前周的日期
  const getWeekDates = () => {
    const today = new Date();
    const currentDay = today.getDay() || 7; // 将周日从0改为7
    const monday = new Date(today);
    monday.setDate(today.getDate() - currentDay + 1);

    const dates = [];
    for (let i = 0; i < 7; i++) {
      const date = new Date(monday);
      date.setDate(monday.getDate() + i);
      dates.push(date);
    }
    return dates;
  };

  const weekDates = getWeekDates();

  // 课程数据 - 修改为新的格式
  const [courseData, setCourseData] = useState({
    1: { // 第1周
      4: [ // 周四 (对应图片中的今日课程)
        {
          id: 1,
          name: '软件建模',
          location: '学习研',
          timeSlot: [3, 4],
          color: '#4ECDC4'
        },
        {
          id: 2,
          name: '思想政治学',
          location: '李斯',
          timeSlot: [7],
          color: '#4A90E2'
        }
      ]
    }
  });

  // 表单数据
  const [addForm] = Form.useForm();

  // 选择器状态
  const [selectedDay, setSelectedDay] = useState(null);
  const [selectedTimeSlots, setSelectedTimeSlots] = useState([]);
  const [selectedColor, setSelectedColor] = useState('#4ECDC4');
  const [selectedType, setSelectedType] = useState('required');
  const [isAddingCourse, setIsAddingCourse] = useState(false);
  const [quickAddCell, setQuickAddCell] = useState(null);

  // 课程模板
  const courseTemplates = [
    { name: '高等数学', teacher: '张教授', location: '教学楼A101', type: 'required', color: '#4ECDC4' },
    { name: '大学英语', teacher: '李老师', location: '外语楼201', type: 'required', color: '#4A90E2' },
    { name: '体育课', teacher: '王教练', location: '体育馆', type: 'required', color: '#7ED321' },
    { name: '专业选修', teacher: '', location: '', type: 'elective', color: '#F5A623' }
  ];

  // 时间段配置 - 修改为10节课
  const timeSlots = [
    { slot: 1, time: '08:30\n09:20' },
    { slot: 2, time: '09:20\n10:10' },
    { slot: 3, time: '10:30\n11:20' },
    { slot: 4, time: '11:20\n12:10' },
    { slot: 5, time: '14:00\n14:50' },
    { slot: 6, time: '14:50\n15:40' },
    { slot: 7, time: '16:00\n16:50' },
    { slot: 8, time: '16:50\n17:40' },
    { slot: 9, time: '19:00\n19:50' },
    { slot: 10, time: '19:50\n20:40' }
  ];

  // 星期配置
  const weekDays = [
    { key: 1, label: '周一', short: '周一', index: 0 },
    { key: 2, label: '周二', short: '周二', index: 1 },
    { key: 3, label: '周三', short: '周三', index: 2 },
    { key: 4, label: '周四', short: '周四', index: 3 },
    { key: 5, label: '周五', short: '周五', index: 4 },
    { key: 6, label: '周六', short: '周六', index: 5 },
    { key: 7, label: '周日', short: '周日', index: 6 }
  ];

  // 课程颜色选项
  const courseColors = [
    { name: '青色', value: '#4ECDC4' },
    { name: '蓝色', value: '#4A90E2' },
    { name: '绿色', value: '#7ED321' },
    { name: '橙色', value: '#F5A623' },
    { name: '红色', value: '#D0021B' },
    { name: '紫色', value: '#9013FE' },
    { name: '粉色', value: '#E91E63' },
    { name: '灰色', value: '#9B9B9B' }
  ];

  // 课程类型选项
  const courseTypes = [
    { label: '必修课', value: 'required' },
    { label: '选修课', value: 'elective' },
    { label: '专业课', value: 'major' },
    { label: '公共课', value: 'public' },
    { label: '实验课', value: 'lab' },
    { label: '实习课', value: 'practice' }
  ];

  // 获取当前周的课程
  const getCurrentWeekCourses = () => {
    return courseData[currentWeek] || {};
  };

  // 检查时间冲突
  const checkTimeConflict = (day, timeSlots, excludeCourseId = null) => {
    const daySchedule = courseData[currentWeek]?.[day] || [];

    for (const existingCourse of daySchedule) {
      if (excludeCourseId && existingCourse.id === excludeCourseId) {
        continue; // 排除当前编辑的课程
      }

      // 检查时间段是否有重叠
      const hasOverlap = timeSlots.some(slot =>
        existingCourse.timeSlot.includes(slot)
      );

      if (hasOverlap) {
        return {
          hasConflict: true,
          conflictCourse: existingCourse
        };
      }
    }

    return { hasConflict: false };
  };

  // 快速添加课程（点击空白格子）
  const handleQuickAddCourse = (day, timeSlot) => {
    const conflict = checkTimeConflict(day, [timeSlot]);
    if (conflict.hasConflict) {
      Toast.show({
        content: `该时间段已有课程：${conflict.conflictCourse.name}`,
        position: 'center'
      });
      return;
    }

    // 设置快速添加的默认值
    setSelectedDay(day);
    setSelectedTimeSlots([timeSlot]);
    setQuickAddCell({ day, timeSlot });
    setShowAddModal(true);
  };

  // 使用课程模板
  const useTemplate = (template) => {
    addForm.setFieldsValue({
      name: template.name,
      teacher: template.teacher,
      location: template.location
    });
    setSelectedType(template.type);
    setSelectedColor(template.color);
    Toast.show({
      content: `已应用模板：${template.name}`,
      position: 'center'
    });
  };

  // 处理课程点击
  const handleCourseClick = (course) => {
    setSelectedCourse(course);
    setShowCourseDetail(true);
  };

  // 添加新课程
  const handleAddCourse = async () => {
    if (isAddingCourse) return; // 防止重复提交

    try {
      setIsAddingCourse(true);
      const values = await addForm.validateFields();

      // 检查必要字段
      if (!selectedDay || !selectedTimeSlots || selectedTimeSlots.length === 0) {
        Toast.show({
          content: '请选择星期和时间段',
          position: 'center'
        });
        return;
      }

      // 检查时间冲突
      const conflict = checkTimeConflict(selectedDay, selectedTimeSlots);
      if (conflict.hasConflict) {
        Toast.show({
          content: `时间冲突！该时间段已有课程：${conflict.conflictCourse.name}`,
          position: 'center'
        });
        return;
      }

      // 验证时间段连续性（可选）
      const sortedTimeSlots = selectedTimeSlots.sort((a, b) => a - b);
      let isConsecutive = true;
      for (let i = 1; i < sortedTimeSlots.length; i++) {
        if (sortedTimeSlots[i] - sortedTimeSlots[i - 1] !== 1) {
          isConsecutive = false;
          break;
        }
      }

      if (!isConsecutive && selectedTimeSlots.length > 1) {
        const confirmResult = await Dialog.confirm({
          content: '选择的时间段不连续，确定要添加吗？',
        });

        if (!confirmResult) {
          return;
        }
      }

      const newCourse = {
        id: Date.now(),
        name: values.name.trim(),
        location: values.location.trim(),
        teacher: values.teacher?.trim() || '',
        type: selectedType || 'required',
        timeSlot: sortedTimeSlots,
        color: selectedColor,
        credit: values.credit || 0,
        description: values.description?.trim() || '',
        createdAt: new Date().toISOString()
      };

      setCourseData(prevData => {
        const newData = { ...prevData };
        if (!newData[currentWeek]) {
          newData[currentWeek] = {};
        }
        if (!newData[currentWeek][selectedDay]) {
          newData[currentWeek][selectedDay] = [];
        }

        newData[currentWeek][selectedDay].push(newCourse);
        return newData;
      });

      // 重置表单和状态
      setShowAddModal(false);
      addForm.resetFields();
      setSelectedDay(null);
      setSelectedTimeSlots([]);
      setSelectedColor('#4ECDC4');
      setSelectedType('required');
      setQuickAddCell(null);

      Toast.show({
        content: '课程添加成功',
        position: 'center'
      });
    } catch (error) {
      console.error('表单验证失败:', error);
      Toast.show({
        content: '添加失败，请检查表单信息',
        position: 'center'
      });
    } finally {
      setIsAddingCourse(false);
    }
  };

  // 切换周次
  const changeWeek = (direction) => {
    if (direction === 'prev' && currentWeek > 1) {
      setCurrentWeek(currentWeek - 1);
    } else if (direction === 'next' && currentWeek < 20) {
      setCurrentWeek(currentWeek + 1);
    }
  };

  // 格式化日期显示
  const formatDate = (date) => {
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${month}/${day}`;
  };

  // 检查是否是今天
  const isToday = (date) => {
    const today = new Date();
    return date.toDateString() === today.toDateString();
  };

  // 渲染课程表格
  const renderScheduleTable = () => {
    const courses = getCurrentWeekCourses();

    return (
      <div className={styles.scheduleContainer}>
        {/* 日期栏 */}
        <div className={styles.dateHeader}>
          {weekDates.map((date, index) => (
            <div
              key={index}
              className={`${styles.dateCell} ${isToday(date) ? styles.today : ''}`}
            >
              <div className={styles.dayLabel}>{weekDays[index]?.short || ''}</div>
              <div className={styles.dateLabel}>{formatDate(date)}</div>
            </div>
          ))}
        </div>

        {/* 课程表格 */}
        <div className={styles.scheduleTable}>
          {timeSlots.map(timeSlot => (
            <div key={timeSlot.slot} className={styles.tableRow}>
              {/* 时间列 */}
              <div className={styles.timeColumn}>
                <div className={styles.slotNumber}>{timeSlot.slot}</div>
                <div className={styles.slotTime}>
                  {timeSlot.time.split('\n').map((time, idx) => (
                    <div key={idx}>{time}</div>
                  ))}
                </div>
              </div>

              {/* 课程列 */}
              {weekDays.map((day) => {
                const dayCourses = courses[day.key] || [];
                const course = dayCourses.find(c =>
                  c.timeSlot.includes(timeSlot.slot)
                );

                return (
                  <div
                    key={day.key}
                    className={`${styles.courseColumn} ${!course ? styles.emptyCell : ''}`}
                    onClick={() => {
                      if (!course) {
                        handleQuickAddCourse(day.key, timeSlot.slot);
                      }
                    }}
                  >
                    {course && course.timeSlot[0] === timeSlot.slot && (
                      <div
                        className={styles.courseBlock}
                        style={{
                          backgroundColor: course.color,
                          height: `${course.timeSlot.length * 60}px`
                        }}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleCourseClick(course);
                        }}
                      >
                        <div className={styles.courseText}>
                          {course.name}@{course.location}
                        </div>
                        {course.teacher && (
                          <div className={styles.courseTeacher}>
                            {course.teacher}
                          </div>
                        )}
                      </div>
                    )}
                    {!course && (
                      <div className={styles.addHint}>
                        <span className={styles.addIcon}>+</span>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className={styles.container}>
      <NavBar
        onBack={() => navigate(-1)}
        className={styles.navBar}
        right={
          <Button
            size="small"
            color="primary"
            fill="none"
            onClick={() => setShowAddModal(true)}
          >
            +
          </Button>
        }
      >
        <div className={styles.weekSelector}>
          <Button
            size="small"
            fill="none"
            onClick={() => changeWeek('prev')}
            disabled={currentWeek <= 1}
            className={styles.weekButton}
          >
            ←
          </Button>
          <span className={styles.weekText}>第{currentWeek}周</span>
          <Button
            size="small"
            fill="none"
            onClick={() => changeWeek('next')}
            disabled={currentWeek >= 20}
            className={styles.weekButton}
          >
            →
          </Button>
        </div>
      </NavBar>

      <div className={styles.content}>
        {renderScheduleTable()}
      </div>

      {/* 课程详情弹窗 */}
      <Modal
        visible={showCourseDetail}
        onClose={() => setShowCourseDetail(false)}
        content={
          selectedCourse && (
            <div className={styles.courseDetail}>
              <h3>{selectedCourse.name}</h3>
              <div className={styles.detailItem}>
                <span className={styles.label}>地点：</span>
                <span>{selectedCourse.location}</span>
              </div>
              <div className={styles.detailItem}>
                <span className={styles.label}>时间：</span>
                <span>第{selectedCourse.timeSlot.join(',')}节</span>
              </div>
            </div>
          )
        }
        actions={[
          {
            key: 'close',
            text: '关闭',
            onClick: () => setShowCourseDetail(false)
          }
        ]}
      />

      {/* 添加课程弹窗 */}
      <Modal
        visible={showAddModal}
        onClose={() => {
          setShowAddModal(false);
          addForm.resetFields();
          setSelectedDay(null);
          setSelectedTimeSlots([]);
          setSelectedColor('#4ECDC4');
          setSelectedType('required');
          setQuickAddCell(null);
        }}
        content={
          <div className={styles.editForm}>
            <h3>{quickAddCell ? '快速添加课程' : '添加课程'}</h3>

            {/* 课程模板 */}
            <div className={styles.templateSection}>
              <div className={styles.templateLabel}>课程模板：</div>
              <div className={styles.templateOptions}>
                {courseTemplates.map((template, index) => (
                  <Button
                    key={index}
                    size="mini"
                    fill="outline"
                    className={styles.templateButton}
                    onClick={() => useTemplate(template)}
                  >
                    {template.name}
                  </Button>
                ))}
              </div>
            </div>

            <Form form={addForm} layout="vertical">
              <Form.Item name="name" label="课程名称" rules={[{ required: true, message: '请输入课程名称' }]}>
                <Input placeholder="请输入课程名称，如：高等数学" />
              </Form.Item>

              <Form.Item name="teacher" label="授课教师">
                <Input placeholder="请输入教师姓名（可选）" />
              </Form.Item>

              <Form.Item name="location" label="上课地点" rules={[{ required: true, message: '请输入上课地点' }]}>
                <Input placeholder="请输入上课地点，如：教学楼A101" />
              </Form.Item>

              <Form.Item label="课程类型">
                <Picker
                  columns={[courseTypes]}
                  value={selectedType ? [selectedType] : []}
                  onConfirm={(value) => {
                    setSelectedType(value[0]);
                  }}
                >
                  {(value) => {
                    if (selectedType) {
                      const courseType = courseTypes.find(type => type.value === selectedType);
                      return courseType ? courseType.label : '必修课';
                    }
                    return '必修课';
                  }}
                </Picker>
              </Form.Item>

              <Form.Item label="星期" required>
                <Picker
                  columns={[weekDays.map(day => ({ label: day.label, value: day.key }))]}
                  value={selectedDay ? [selectedDay] : []}
                  onConfirm={(value) => {
                    setSelectedDay(value[0]);
                  }}
                >
                  {(value) => {
                    if (selectedDay) {
                      const day = weekDays.find(d => d.key === selectedDay);
                      return day ? day.label : '请选择星期';
                    }
                    return '请选择星期';
                  }}
                </Picker>
              </Form.Item>

              <Form.Item label="时间段" required>
                <Picker
                  columns={[timeSlots.map(slot => ({ label: `第${slot.slot}节 (${slot.time.replace('\n', '-')})`, value: slot.slot }))]}
                  value={selectedTimeSlots}
                  multiple
                  onConfirm={(value) => {
                    setSelectedTimeSlots(value);
                  }}
                >
                  {(value) => {
                    if (selectedTimeSlots && selectedTimeSlots.length > 0) {
                      const slots = selectedTimeSlots.sort((a, b) => a - b);
                      return `第${slots.join(',')}节 (${selectedTimeSlots.length}节课)`;
                    }
                    return '请选择时间段';
                  }}
                </Picker>
              </Form.Item>

              <Form.Item label="课程颜色">
                <div className={styles.colorPicker}>
                  {courseColors.map((color) => (
                    <div
                      key={color.value}
                      className={`${styles.colorOption} ${selectedColor === color.value ? styles.colorSelected : ''}`}
                      style={{ backgroundColor: color.value }}
                      onClick={() => setSelectedColor(color.value)}
                      title={color.name}
                    />
                  ))}
                </div>
              </Form.Item>

              <div className={styles.formRow}>
                <Form.Item name="credit" label="学分" className={styles.halfWidth}>
                  <Input type="number" placeholder="学分" min="0" max="10" step="0.5" />
                </Form.Item>
              </div>

              <Form.Item name="description" label="备注">
                <Input placeholder="课程描述或备注（可选）" />
              </Form.Item>
            </Form>
          </div>
        }
        actions={[
          {
            key: 'add',
            text: isAddingCourse ? '添加中...' : '添加课程',
            color: 'primary',
            onClick: handleAddCourse,
            loading: isAddingCourse
          },
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              setShowAddModal(false);
              addForm.resetFields();
              setSelectedDay(null);
              setSelectedTimeSlots([]);
              setSelectedColor('#4ECDC4');
              setSelectedType('required');
              setQuickAddCell(null);
            }
          }
        ]}
      />
    </div>
  );
}

export default CourseSchedule;